package com.wyd.observer.demo02;

import com.wyd.observer.demo02.Observer.Observer;
import com.wyd.observer.demo02.Subject.Subject;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Yudi Wang
 * @date 2022/1/6 11:17
 */
public class WeatherData implements Subject {

    private int temperature;

    private int pressure;

    private List<Observer> observers;

    public WeatherData() {
        this.observers = new ArrayList<Observer>();
    }

    /**
     * 便于观察者自行获取数据
     *
     * @return
     */
    public int getTemperature() {
        return temperature;
    }

    public int getPressure() {
        return pressure;
    }

    /**
     * 注册观察者
     *
     * @param observer
     */
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    /**
     * 移除观察者
     *
     * @param observer
     */
    public void removeObserver(Observer observer) {
        int i = observers.indexOf(observer);
        if (i != -1) {
            observers.remove(i);
        }
    }

    /**
     * 通知所有订阅的观察者
     * 依赖接口 Observer
     * 可动态增删观察者
     * update接口基本问题，发布者暴露数据，由观察者主动拉去数据
     */
    public void notifyObserver() {
        for (Observer observer : observers) {
            observer.update(this);
        }
    }

    /**
     * 模拟监测值发生变化
     *
     * @param temperature
     * @param pressure
     */
    public void setMessureData(int temperature, int pressure) {
        this.temperature = temperature;
        this.pressure = pressure;
        messureDataChanged();
    }

    /**
     * 监测值发生变化时调用
     */
    private void messureDataChanged() {
        notifyObserver();
    }

    public static void main(String[] args) {
        /**
         * 发布者
         */
        WeatherData weatherData = new WeatherData();
        /**
         * 实例化，并注册
         */
        PressureDisplay pressureDisplay = new PressureDisplay(weatherData);
        TemperatureDisplay temperatureDisplay = new TemperatureDisplay(weatherData);
        /**
         * 模拟监测值发生变化
         * 相关看板应该同步显示变化的监测值
         */
        weatherData.setMessureData(22, 101010);
    }
}
